package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Destination;
import cn.wolfcode.luowowo.domain.Travel;
import cn.wolfcode.luowowo.query.TravelCondition;
import cn.wolfcode.luowowo.query.TravelQuery;
import cn.wolfcode.luowowo.repository.TravelRepository;
import cn.wolfcode.luowowo.service.IDestinationService;
import cn.wolfcode.luowowo.service.ITravelService;
import cn.wolfcode.luowowo.service.IUserInfoService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;


@Service
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelRepository travelRepository;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IDestinationService destinationService;

    @Override
    public Page<Travel> query(TravelQuery qo) {
        Query query = new Query();

        // 按照状态筛选数据
        if(qo.getState() > 0){
            query.addCriteria(Criteria.where("state").is(qo.getState()));
        }

        // 按照天数筛选数据
        TravelCondition day = qo.getDay();  // 获取传输过来的天数筛选条件
        if(day != null){
            query.addCriteria(Criteria.where("day").gte(day.getMin()).lte(day.getMax()));
        }


        // 按照人均消费筛选数据
        TravelCondition perExpend = qo.getPerExpend();// 获取传输过来人均花费参数
        if(perExpend != null){
            query.addCriteria(Criteria.where("perExpend").gte(perExpend.getMin()).lte(perExpend.getMax()));
        }

        String order = "_id";
        if(qo.getOrderType() == TravelQuery.ORDER_NEW){
            order = "release_Time";
        }else if(qo.getOrderType() == TravelQuery.ORDER_HOT){
            order = "viewnum";
        }
        PageRequest request = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.DESC, order);
        Page<Travel> list = DBHelper.query(template, Travel.class, query, request);
        for (Travel travel : list) {
            travel.setAuthor(userInfoService.get(travel.getUserId()));

        }
        return list;

    }


    @Override
    public Travel getContentById(String id) {
        return travelRepository.findById(id).orElse(null);
    }

    @Override
    public void changeState(String id, int state) {
        // 1.检查游记是否存在
        Travel travel = this.getContentById(id);
        if(travel != null){
            // 2.如果当前状态是待审核
            if(travel.getState() == travel.STATE_WAITING) {
                // 3.并且进行的操作是 审核通过或者审核拒绝
                if(state == travel.STATE_RELEASE || state == travel.STATE_REJECT){
                    // 如果是通过 更新尕布时间为当前时间
                    if(state == travel.STATE_RELEASE){
                        travel.setReleaseTime(new Date());      // 更新发布时
                    }else{
                        // 如果是拒绝,发布时间更新为null
                        travel.setReleaseTime(null);
                    }
                    // 需要更新的数据
                    travel.setState(state);                 // 更新游记状态
                    travel.setLastUpdateTime(new Date());   // 最后更新时间
                    travelRepository.save(travel);
                }
            }else if(travel.getState() == travel.STATE_RELEASE){    // 如果当前状态是已发布
                // 并且操作是 下架
                if(state == travel.STATE_SHELF){
                    // 进行下架操作
                    travel.setReleaseTime(null);            // 更新发布时
                    travel.setState(state);                 // 更新游记状态
                    travel.setLastUpdateTime(new Date());   // 最后更新时间
                    travelRepository.save(travel);
                }
            }
        }
    }

    @Override
    public Travel get(String id) {
        Optional<Travel> op = travelRepository.findById(id);
        if (op.isPresent()){
            Travel travel = op.get();
            travel.setAuthor(userInfoService.get(travel.getUserId()));
            travel.setDest(destinationService.get(travel.getDestId()));
            return travel;
        }

        return null;
    }

    @Override
    public void saveOrUpdate(Travel travel) {

        // 目的地
        Destination destination = destinationService.get(travel.getDestId());
        travel.setDestName(destination.getName());

        // 发表用户
        // 最后更新时间
        travel.setLastUpdateTime(new Date());


        if (StringUtils.hasLength(travel.getId())) {
            // 更新
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(travel.getId()));
            DBHelper.update(template,query,travel,"destId","destName","title",
                    "coverUrl","travelTime","perExpend",
                    "day","person","lastUpdateTime",
                    "isPublic","state","summary","content");


        }else{
            // 添加
            travel.setCreateTime(new Date());
            travel.setId(null);
            travelRepository.save(travel);
        }
    }

    @Override
    public List<Travel> findByDestIdOrderByDesc(String destId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("destId").is(destId));
        PageRequest viewnum = PageRequest.of(0, 3, Sort.Direction.DESC, "viewnum");
        List<Travel> travels = travelRepository.findByDestId(destId, viewnum);
        return travels;
    }

    @Override
    public List<Travel> list() {
        return travelRepository.findAll();

    }

    @Override
    public List<Travel> getByDestName(String keyword) {
        return travelRepository.findByDestName(keyword);
    }
}
